package com.ybkj.daijia.server.service.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.config.PartnerApi;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.partner.Partner;
import com.ybkj.daijia.server.service.PartnerService;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DefaultPartnerService implements PartnerService {

    @Autowired
    private PartnerApi partnerApi;
    @Autowired
    private SettingUtils settingUtils;

    @Override
    public Page<Partner> findByParam(String categoryAlias, Long intentId, String param, Date start,
        Date end) {
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        StringBuilder sb = new StringBuilder();
        sb.append(partnerApi.getPartnerBaseURL() + PartnerApi.QUERY_PARTNER
            + "?appKey={appKey}&appId={appId}&sign={sign}&page={page}&rows={rows}&categoryAlias={categoryAlias}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        kv.put("categoryAlias", categoryAlias);
        if (intentId != null && intentId != 0) {
            kv.put("intentId", String.valueOf(intentId));
            sb.append("&intentId={intentId}");
        }
        if (start != null) {
            kv.put("start", String.valueOf(start.getTime()));
            sb.append("&start={start}");
        }
        if (end != null) {
            kv.put("end", String.valueOf(end.getTime()));
            sb.append("&end={end}");
        }
        if (StringUtils.isNotBlank(param)) {
            kv.put("param", param);
            sb.append("&param={param}");
        }

        String result = partnerApi.get(sb.toString(), kv, settingUtils.get());
        List<Partner> list = new ArrayList<Partner>();
        long total = 0;

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new Gson();
                list = gson.fromJson(ja.toString(), new TypeToken<List<Partner>>() {
                }.getType());
            }
        }
        return new PageImpl<Partner>(list, pageable, total);
    }

    @Override
    public Partner save(Partner partner, List<String> imgs) {
        StringBuilder builder = new StringBuilder();
        builder.append(partnerApi.getPartnerBaseURL() + PartnerApi.SAVE_PARTNER
            + ".json?appKey={appKey}&appId={appId}&sign={sign}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("categoryAlias", partner.getCategoryAlias());
        builder.append("&categoryAlias={categoryAlias}");
        if (partner.getIntentId() != null) {
            kv.put("intentId", String.valueOf(partner.getIntentId()));
            builder.append("&intentId={intentId}");
        }
        kv.put("name", partner.getName());
        builder.append("&name={name}");
        kv.put("phone", partner.getPhone());
        builder.append("&phone={phone}");
        kv.put("address", partner.getAddress());
        builder.append("&address={address}");
        kv.put("city", partner.getCity());
        builder.append("&city={city}");
        kv.put("province", partner.getProvince());
        builder.append("&province={province}");
        kv.put("lat", String.valueOf(partner.getLat()));
        builder.append("&lat={lat}");
        kv.put("lng", String.valueOf(partner.getLng()));
        builder.append("&lng={lng}");
        kv.put("intro", partner.getIntro());
        builder.append("&intro={intro}");
        kv.put("county", partner.getCounty());
        builder.append("&county={county}");

        String result = partnerApi.post(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                partner.setId(data.getLong("id"));

                Long partnerId = data.getLong("id");
                //保存图片
                for (String img : imgs) {
                    if (StringUtils.isNotBlank(img)) {
                        builder.setLength(0);
                        kv.clear();
                        builder.append(partnerApi.getPartnerBaseURL() + PartnerApi.SAVE_PARTNERIMG
                            + ".json?appKey={appKey}&appId={appId}&sign={sign}");
                        kv.put("partnerId", String.valueOf(partnerId));
                        builder.append("&partnerId={partnerId}");
                        kv.put("img", img);
                        builder.append("&img={img}");

                        result = partnerApi.post(builder.toString(), kv, settingUtils.get());
                        if (null != result) {
                            jo = new JSONObject(result);
                            code = jo.getInt("code");
                            if (code == 0) {
                                data = jo.getJSONObject("data");
                            }
                        }
                    }
                }

                return partner;
            } else {
                return null;
            }
        }
        return null;
    }

    @Override
    public Partner update(Partner partner, List<String> imgs) {
        StringBuilder builder = new StringBuilder();
        builder.append(partnerApi.getPartnerBaseURL() + PartnerApi.UPDATE_PARTNER + partner.getId()
            + "?appKey={appKey}&appId={appId}&sign={sign}");
        Map<String, String> kv = new HashMap<String, String>();
        if (partner.getIntentId() != null) {
            kv.put("intentId", String.valueOf(partner.getIntentId()));
            builder.append("&intentId={intentId}");
        }
        kv.put("name", partner.getName());
        builder.append("&name={name}");
        kv.put("phone", partner.getPhone());
        builder.append("&phone={phone}");
        kv.put("address", partner.getAddress());
        builder.append("&address={address}");
        kv.put("city", partner.getCity());
        builder.append("&city={city}");
        kv.put("county", partner.getCounty());
        builder.append("&county={county}");
        kv.put("province", partner.getProvince());
        builder.append("&province={province}");
        kv.put("lat", String.valueOf(partner.getLat()));
        builder.append("&lat={lat}");
        kv.put("lng", String.valueOf(partner.getLng()));
        builder.append("&lng={lng}");
        kv.put("intro", partner.getIntro());
        builder.append("&intro={intro}");

        //删除旧图片文件
//    	Partner temp = findById(partner.getId());
//    	List<PartnerImg> list = temp.getList();
//    	if(list!=null && list.size()!=0){
//	    	for (PartnerImg partnerImg : list) {
//	    		PhotoDeleteUtil.deleteFile(partnerImg.getImg());
//	    	}
//    	}

        String result = partnerApi.put(builder.toString(), kv, settingUtils.get());

        if (StringUtils.isBlank(result)) {
            Long partnerId = partner.getId();
            //保存图片
            for (String img : imgs) {
                if (StringUtils.isNotBlank(img)) {
                    builder.setLength(0);
                    kv.clear();
                    builder.append(partnerApi.getPartnerBaseURL() + PartnerApi.SAVE_PARTNERIMG
                        + ".json?appKey={appKey}&appId={appId}&sign={sign}");
                    kv.put("partnerId", String.valueOf(partnerId));
                    builder.append("&partnerId={partnerId}");
                    kv.put("img", img);
                    builder.append("&img={img}");

                    result = partnerApi.post(builder.toString(), kv, settingUtils.get());
                    if (null != result) {
                        JSONObject jo = new JSONObject(result);
                        int code = jo.getInt("code");
                        if (code == 0) {
                            JSONObject data = jo.getJSONObject("data");
                        }
                    }
                }
            }

            return partner;
        }
        return null;
    }

    @Override
    public String delete(Long id) {
        StringBuilder sb = new StringBuilder();
        sb.append(partnerApi.getPartnerBaseURL() + PartnerApi.DELETE_PARTNER + id
            + "?appKey={appKey}&appId={appId}&sign={sign}");
        Map<String, String> kv = new HashMap<String, String>();
        String delete = partnerApi.delete(sb.toString(), kv, settingUtils.get());
        return delete;
    }

    @Override
    public String deleteIntent(Long id) {
        StringBuilder sb = new StringBuilder();
        sb.append(partnerApi.getPartnerBaseURL() + PartnerApi.DELETE_INTENT + id
            + "?appKey={appKey}&appId={appId}&sign={sign}");
        Map<String, String> kv = new HashMap<String, String>();
        String delete = partnerApi.delete(sb.toString(), kv, settingUtils.get());
        return delete;
    }

    @Override
    public Partner findById(Long id) {
        Partner partner = new Partner();
        StringBuilder sb = new StringBuilder();
        sb.append(partnerApi.getPartnerBaseURL() + PartnerApi.QUERY_ONE
            + "?appKey={appKey}&appId={appId}&sign={sign}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("id", String.valueOf(id));
        sb.append("&id={id}");
        String string = partnerApi.get(sb.toString(), kv, settingUtils.get());
        JSONObject jo = new JSONObject(string);
        Integer code = jo.getInt("code");
        if (code == 0) {
            JSONObject data = jo.getJSONObject("data");
            Gson gson = new Gson();
            partner = gson.fromJson(data.toString(), new TypeToken<Partner>() {
            }.getType());
            return partner;
        } else {
            return null;
        }

    }

}